layui.use(['table', 'admin', 'ax','laydate','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var form = layui.form;

    laydate.render({
        elem: '#startTime'
        ,value:new Date()
    });

    laydate.render({
        elem: '#endTime'
        ,value:new Date()
    });

    /**
     * 调度单表管理
     */
    var carrierRecDetail = {
        tableId: "carrierRecDetailTable"
    };

    /**
     * 初始化表格的列
     */
    carrierRecDetail.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'recState', title: '流程状态', sort: true,templet: '#recStateTpl'},
            {field: 'operateName', title: '项目', style:'font-weight: 600;'},
            {field: 'trainNumber', title: '车次', style:'font-weight: 600;', sort: true},
            {field: 'startDate', title: '发车日期', style:'font-weight: 600;', sort: true},
            {field: 'daocangTimes', title: '到仓时间', sort: true},
            {field: 'fayunTimes', title: '发运时间', sort: true},
            {field: 'dispatchNumber', title: '运输单号', style:'font-weight: 600;'},
            {field: 'customerOrder', title: '客户单号', style:'font-weight: 600;'},
            {field: 'carnumber', title: '车牌号', style:'font-weight: 600;', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'driver1', title: '司机', style:'font-weight: 600;', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'tel1', title: '联系方式', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'privatecarType', title: '车型', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'mileageTraveled', title: '行驶里程', style:'background-color: #dbf1e1;font-weight: 600;', sort: true},
            {field: 'mileageTraveledTyp', title: '行驶里程分段', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'loadingType', title: '装车方', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'loadingPersonnel', title: '装车人员', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'privatecarSurevolume', title: '准载方数m3', style:'background-color: #dbf1e1;font-weight: 600;', sort: true},
            {field: 'getUnit', title: '收货客户', style:'font-weight: 600;',width:180},
            {field: 'kilometer', title: '公里数', style:'font-weight: 600;'},
            {field: 'shi', title: '城市', style:'font-weight: 600;'},
            {field: 'qu', title: '区县', style:'font-weight: 600;'},
            {field: 'tooDeployVolume', title: '方数m3', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'toovolume', title: '总方数m3', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'matrixingNumber', title: '件数', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'matrixingNumberSum', title: '总件数', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'pieceNumber', title: '整件+拆零封箱数', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'pieceNumberSum', title: '整件+拆零封箱数合计', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'carrierName', sort: true, title: '承运商', style:'font-weight: 600;'},
            {field: 'lineName', sort: true, title: '线路', style:'font-weight: 600;'},
            {field: 'freightMoney', sort: true, title: '总运费￥', style:'font-weight: 600;', totalRow: true},
            {field: 'consultMoney', title: '参考运费￥', style:'font-weight: 600;',totalRow: true},
            {field: 'loadingMoney', sort: true, title: '装车费￥', style:'font-weight: 600;', totalRow: true},
            {field: 'xiechefei', sort: true, title: '卸车费￥', style:'font-weight: 600;', totalRow: true},
        ]];
    };

    /**
     * 导出excel按钮
     */
    carrierRecDetail.exportExcel = function () {
        var checkRows = table.checkStatus(carrierRecDetail.tableId);
        if (checkRows.data.length > 0) {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        } else {
            var queryData = {};
            queryData['operateId'] = $("#operateId").val();
            queryData['getUnit'] = $("#getUnit").val();
            queryData['condition'] = $("#condition").val();
            queryData['startTime'] = $("#startTime").val();
            queryData['endTime'] = $("#endTime").val();
            queryData['operateName'] = $("#operateName").val();
            queryData['carrierName'] = $("#carrierName").val();
            $.ajax({
                type: "POST",
                url: Feng.ctxPath + "/rec/carrierRecDetail/listAll",
                dataType:'json',
                data: queryData,
                beforeSend: function () {
                    //弹出加载中
                    index = layer.load(1, {
                        shade: [0.3, '#000'] //0.1透明度的白色背景
                    });
                },
                success: function (data) {
                    checkRows.data = data;
                    table.exportFile(tableResult.config.id, checkRows.data, 'xls');
                    layer.close(index);
                },
                error: function (data) {
                    console.log(data)
                }
            });
        }
    };

    // 导出excel
    $('#btnExp').click(function () {
        carrierRecDetail.exportExcel();
    });

    /**
     * 点击查询按钮
     */
    carrierRecDetail.search = function () {
        var queryData = {};
        queryData['operateId'] = $("#operateId").val();
        queryData['getUnit'] = $("#getUnit").val();
        queryData['condition'] = $("#condition").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['operateName'] = $("#operateName").val();
        queryData['carrierName'] = $("#carrierName").val();
        queryData['carrierId'] = $("#carrierId").val();
        queryData['recState'] = $("#recState").val();
        queryData['customerOrder'] = $("#customerOrder").val();
        table.reload(carrierRecDetail.tableId, {
            where: queryData, page: {curr: 1},
            done: function (res, curr, count) {
            }
        });
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + carrierRecDetail.tableId,
        url: Feng.ctxPath + "/rec/carrierRecDetail/listPage",
        page: true,
        limit: 60,
        limits:[60,120,240,360,480,1500,5000],
        height: "full-60",
        // totalRow: true,
        // toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        defaultToolbar: ['filter', 'exports', 'print'],
        cellMinWidth: 100,
        cols: carrierRecDetail.initColumn(),
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        carrierRecDetail.search();
    });

    // 单击行事件
    table.on('row(' + carrierRecDetail.tableId + ')', function (obj) {
        var data = obj.data;
        $('div[lay-id="' + carrierRecDetail.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
        $('div[lay-id="' + carrierRecDetail.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
    });

    // 工具条点击事件
    table.on('tool(' + carrierRecDetail.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'tooDetailed') {
            layer.open({
                type: 2,
                title: '配送派车信息',
                area: ['1250px', '570px'],
                anim: 5,
                content: Feng.ctxPath + '/carrierRecDetail/tooDetailed?dispatchNumber=' + data.dispatchNumber,
            });
        } else if (layEvent === 'tooConsultMoneyDetailed') {
            layer.open({
                type: 2,
                title: '费用信息',
                area: ['1100px', '500px'],
                anim: 5,
                content: Feng.ctxPath + '/transportCost?dispatchNumber=' + data.dispatchNumber,
            });
        } else if (layEvent === 'audit'){
            var item = data;

            if (item.recState !== '待审核'){
                layer.msg('该单据已在流程中', {icon: 0}, function(){
                    return;
                });
            }
            // 弹出输入框让用户输入审核意见或备注
            layer.prompt({
                title: '请输入审核意见或备注',
                formType: 2,
                value: '', // 设置默认值为空
                maxlength: 100
            }, function (value, index, elem) {
                // 构建审核数据
                var auditData = {
                    operateId: item.operateId,
                    operateName: item.operateName,
                    startDate: item.startDate,
                    dispatchNumber: item.dispatchNumber,
                    carrierId: item.carrierId,
                    carrierName: item.carrierName,
                    driver1: item.driver1,
                    tel1: item.tel1,
                    carnumber: item.carnumber,
                    privatecarType: item.privatecarType,
                    mileageTraveled: item.mileageTraveled,
                    totalVolume: item.toovolume,
                    totalPieces: item.matrixingNumber,
                    pieceNumberSum: item.pieceNumberSum,
                    freightMoney: item.freightMoney,
                    consultMoney: item.consultMoney,
                    loadingMoney: item.loadingMoney,
                    unloadingMoney: item.xiechefei,
                    notes: value || ''
                };

                // 发送审核请求
                var ajax = new $ax(Feng.ctxPath + "/rec/carrierRecDetail/audit", function (response) {
                    Feng.success(response.message);
                    table.reload(carrierRecDetail.tableId);
                }, function (error) {
                    Feng.error("审核失败: " + error.responseJSON.message);
                });
                ajax.setData(auditData);
                ajax.start();

                // 关闭输入框
                layer.close(index);
            });
        }
    });

    //查询库区
    form.on('select(operateId)',function(){
        $("#carrierId").empty();
        $.ajax({
            url:Feng.ctxPath + '/basicCarrier/Querylist',
            dataType:"json",   //返回格式为json
            async: false,
            data:{"operateId":$("#operateId").val()},    //参数值
            type:"post",   //请求方式
            success:function(data){
                if(data.length>0){
                    var str = "<option value=''>选择承运商</option>";
                    $.each(data,function(key,value){
                        str += "<option value='"+value.id+"'>"+value.carrierName+"</option>";
                    });
                    $("#carrierId").html(str);
                }
            }
        });
        form.render('select');
    });

    $('#btnAudit').click(function () {
        carrierRecDetail.btnAudit();
    })


    // 批量审核
    carrierRecDetail.btnAudit = function () {
        var checkStatus = table.checkStatus(carrierRecDetail.tableId);
        var data = checkStatus.data;

        if (data.length === 0) {
            layer.alert('请至少选中一条记录进行审核', {icon: 0});
            return;
        }

        console.log("data:",data)

        // 检查哪些记录是无效的
        var invalidRecords = data.filter(function(item) {
            return item.operateName !== '' && item.recState === '待审核';
        });

        console.log("invalidRecords:",invalidRecords)

        // 弹出输入框让用户输入审核意见或备注
        layer.prompt({
            title: '请输入审核意见或备注',
            formType: 2,
            value: '', // 设置默认值为空
            maxlength: 100
        }, function (value, index, elem) {
            // 构建审核数据列表
            var auditDataList = invalidRecords.map(function(item) {
                return {
                    operateId: item.operateId,
                    operateName: item.operateName,
                    startDate: item.startDate,
                    dispatchNumber: item.dispatchNumber,
                    carrierId: item.carrierId,
                    carrierName: item.carrierName,
                    driver1: item.driver1,
                    tel1: item.tel1,
                    carnumber: item.carnumber,
                    privatecarType: item.privatecarType,
                    mileageTraveled: item.mileageTraveled,
                    totalVolume: item.totalVolume,
                    totalPieces: item.totalPieces,
                    pieceNumberSum: item.pieceNumberSum,
                    freightMoney: item.freightMoney,
                    consultMoney: item.consultMoney,
                    loadingMoney: item.loadingMoney,
                    unloadingMoney: item.unloadingMoney,
                    notes: value || ''
                };
            });

            console.log("auditDataList:",auditDataList)

            $.ajax({
                url: Feng.ctxPath + "/rec/carrierRecDetail/batchAudit",
                type: "POST",
                // data: JSON.stringify({ auditDataList: auditDataList }),
                data: JSON.stringify(auditDataList),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    layer.msg(data.message);
                    table.reload(carrierRecDetail.tableId);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(errorThrown);
                    layer.msg(jqXHR.responseText);
                }
            });

            // 关闭输入框
            layer.close(index);
        });
    };


});
